// 导航守卫
import router from '@/router/index.js'
import store from '@/store/index.js'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { cancelAll } from '@/utils/request'
const pageArr = ['/404', '/login']
// 前置守卫
router.beforeEach(async(to, from, next) => {
  cancelAll()
  NProgress.start()
  // to and from are both route objects. must call `next`.
  if (store.state.user.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (pageArr.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + encodeURIComponent(to.fullPath))
    }
  }
  NProgress.done()
})

// 后置守卫
router.afterEach((to, from) => {
  NProgress.done()
  // to and from are both route objects.
})
